import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => MyAppState(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
          useMaterial3: true,
        ),
        home: const MyHomePage(),
      ),
    );
  }
}

class MyAppState extends ChangeNotifier {
  var current = WordPair.random();
  Map<WordPair, bool> favorites = {};

  void getNext() {
    if (!favorites.containsKey(current)) {
      favorites[current] = false;
    }
    current = WordPair.random();
    notifyListeners();
  }

  void toggleFavorite() {
    if (!favorites.containsKey(current) || favorites[current] == false) {
      favorites[current] = true;
    } else {
      favorites[current] = false;
    }
    notifyListeners();
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var selected = 0;
  @override
  Widget build(BuildContext context) {
    Widget widget;
    switch (selected) {
      case 0:
        widget = GeneratorPage();
        break;
      case 1:
        widget = FavoritesPage();
        break;
      default:
        throw UnimplementedError('no widget for $selected');
    }
    return LayoutBuilder(builder: (context, constraints) {
      return Scaffold(
        body: Row(
          children: [
            SafeArea(
              child: NavigationRail(
                extended: constraints.maxWidth >= 600,
                destinations: [
                  NavigationRailDestination(
                    icon: Icon(Icons.home),
                    label: Text('Home'),
                  ),
                  NavigationRailDestination(
                    icon: Icon(Icons.favorite),
                    label: Text('Favorites'),
                  ),
                ],
                selectedIndex: selected,
                onDestinationSelected: (value) {
                  setState(() {
                    selected = value;
                  });
                },
              ),
            ),
            Expanded(
              child: Container(
                color: Theme.of(context).colorScheme.primaryContainer,
                child: widget,
              ),
            ),
          ],
        ),
      );
    });
  }
}

class GeneratorPage extends StatelessWidget {
  const GeneratorPage({super.key});

  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();
    var pair = appState.current;
    var favorites = appState.favorites;
    IconData icon;
    if (favorites.containsKey(pair) && favorites[pair] == true) {
      icon = Icons.favorite;
    } else {
      icon = Icons.favorite_border;
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Text('A random AWESOME idea:'),
          Expanded(
            flex: 4,
            child: WordList(),
          ),
          Expanded(
            flex: 5,
            child: Column(
              children: [
                BigCard(pair: pair),
                const SizedBox(height: 10),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ElevatedButton.icon(
                      onPressed: () {
                        appState.toggleFavorite();
                      },
                      icon: Icon(icon),
                      label: Text('Like'),
                    ),
                    const SizedBox(width: 10),
                    ElevatedButton(
                      onPressed: () {
                        appState.getNext();
                      },
                      child: Text('Next'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class BigCard extends StatelessWidget {
  const BigCard({
    super.key,
    required this.pair,
  });

  final WordPair pair;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final style = theme.textTheme.displayMedium!.copyWith(
      color: theme.colorScheme.onPrimary,
    );
    return Card(
      color: theme.colorScheme.primary,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Text(
          pair.asLowerCase,
          style: style,
          semanticsLabel: "${pair.first} ${pair.second}",
        ),
      ),
    );
  }
}

// 为了实现自动滚动到最下的效果，将widget改为stateless改为stateful
class WordList extends StatefulWidget {
  const WordList({super.key});

  @override
  State<WordList> createState() => _WordListState();
}

class _WordListState extends State<WordList> {
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();
    var favorites = appState.favorites;
    return ListView.builder(
      controller: _scrollController,
      itemCount: favorites.length,
      itemBuilder: (context, index) {
        var pair = favorites.keys.elementAt(index);
        return ListTile(
          leading: favorites[pair] == true ? const Icon(Icons.favorite) : const Text(' '),
          title: Text(pair.asLowerCase),
        );
      },
    );
  }

  @override
  void didUpdateWidget(covariant WordList oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Scroll to the bottom whenever the widget updates
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }
}

// Favorites page
class FavoritesPage extends StatelessWidget {
  const FavoritesPage({super.key});

  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();
    if (appState.favorites.isEmpty) {
      return Center(
        child: Text('No favorites yet.'),
      );
    }
    final favorites = appState.favorites.entries
        .where((element) => element.value == true)
        .map((e) => e.key)
        .toList();
    return ListView(children: [
      Padding(
        padding: const EdgeInsets.all(20),
        child: Text('You have ${favorites.length} favorites:'),
      ),
      ...favorites.map(
        (pair) => ListTile(
          leading: const Icon(Icons.favorite),
          title: Text(pair.asLowerCase),
        ),
      ),
    ]);
  }
}
